﻿using AnlianCommon.Common.Domains.OrganizationalUnits;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.Departments
{
    public class DepartmentTreeSerrchHander : IRequestHandler<DepartmentTreeSerrchCommand, Result>
    {
        private readonly IBaseRepository<DepartmentType> departmentTypeRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentTypeRepository"></param>
        public DepartmentTreeSerrchHander(IBaseRepository<DepartmentType> departmentTypeRepository)
        {
            this.departmentTypeRepository = departmentTypeRepository;
        }
        /// <summary>
        /// 设置部门类型级联
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(DepartmentTreeSerrchCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            var list = await (await departmentTypeRepository.GetAll()).Where(x => x.Pid == 0).ToListAsync();
            List<Tree> trees = new List<Tree>();
            foreach (var item in list)
            {
                Tree tree = new Tree();
                tree.value = item.DepartmentTypeId;
                tree.label = item.DepartmentTypeName;
                tree.children =await GetTree(item.DepartmentTypeId);
                trees.Add(tree);
            }
            result.Data = trees;
            return result;

        }
        public async Task<List<Tree>> GetTree(int pid = 0)
        {
            var list = await (await departmentTypeRepository.GetAll()).Where(x => x.Pid == pid).ToListAsync();
            List<Tree> trees = new List<Tree>();
            foreach (var item in list)
            {
                Tree tree = new Tree();
                tree.value = item.DepartmentTypeId;
                tree.label = item.DepartmentTypeName;
                tree.children =await GetTree(item.DepartmentTypeId);
                trees.Add(tree);
            }
            return trees;
        }
    }
}
